<script setup lang="ts">
import { ref,onMounted,onUnmounted } from 'vue';
import {
  get,
  post,
  postUploadFiles,
  postUploadFile,
  baseURL,
} from "./utils/api";

const messageListRef = ref<HTMLElement|null>(null);
// 消息列表
const messages = ref<string[]>([]);
// 输入框内容
const inputMessage = ref<string>('');

onMounted(async () => {
  
});


onUnmounted(async () => {

});

// 发送消息
const sendMessage = async() => {
  if (inputMessage.value.trim()) {
    messages.value.push(inputMessage.value);
    const response = await post<{ list: object }>(
      "/send_bailian_message",
      { message:inputMessage.value }
    );
    // console.log(JSON.parse(response).data);
    // const result = JSON.parse(response);
    // console.log(result.content);
    // inputMessage.value = '';
    messages.value.push(response);

    nextTick(() => {
      if (messageListRef.value) {
        console.log("scrollTop",messageListRef.value.scrollHeight)
        messageListRef.value.scrollTop = messageListRef.value.scrollHeight;
      } else {
        console.log("messageListRef is null");
      }
    });
  }
};


// 上传文件
const handleFileUpload = (event: Event) => {
  const target = event.target as HTMLInputElement;
  if (target.files && target.files.length > 0) {
    const file = target.files[0];
    messages.value.push(`[文件] ${file.name}`);
    target.value = ''; // 重置文件输入
  }
};
</script>

<template>
  <div class="chat-container">
    <div ref="messageListRef" class="message-list">
      <div v-for="(message, index) in messages" :key="index" class="message">
        {{ message }}
      </div>
    </div>
    <div class="input-area">
      <input type="file" @change="handleFileUpload" class="file-upload" />
      <input v-model="inputMessage" type="text" placeholder="输入消息..." class="message-input" />
      <button @click="sendMessage" class="send-button">发送</button>
    </div>
  </div>
</template>

<style scoped>
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: 90vh; /* 使容器占满整个视口高度 */
  width: 100%;
  border: 1px solid #ccc;
  padding: 10px;
  box-sizing: border-box; /* 确保内边距和边框不会增加高度 */
}

.message-list {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 10px;
}

.message {
  margin: 5px 0;
  padding: 10px;
  background-color: #f1f1f1;
  border-radius: 5px;
}

.input-area {
  display: flex;
}

.file-upload {
  margin-right: 10px;
}

.message-input {
  flex: 1;
  padding: 10px;
  margin-right: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.send-button {
  padding: 10px 20px;
  border: none;
  background-color: #007bff;
  color: white;
  border-radius: 5px;
  cursor: pointer;
}

.send-button:hover {
  background-color: #0056b3;
}
</style>